﻿using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json.Linq;
using Serilog;
using Swashbuckle.AspNetCore.SwaggerUI;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Reflection;
using System.Web;
using XinLife.Core.Extention;
using XinLife.Core.Helper;

namespace XinLife.Common.Filters
{
    public static class SwaggerMiddleware
    {
        public static void UseSwaggerMiddle(this IApplicationBuilder app)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));

            app.UseSwagger();

            //原始SwaggerUI
            //app.UseSwaggerUI(options =>
            //{
            //    options.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
            //    options.DocumentTitle = Appsettings.app(new string[] { "SwaggerDoc", "Title" });
            //    new string[] { "XinLife" }.ToList().ForEach(version =>
            //    {
            //        options.SwaggerEndpoint($"../swagger/{version}/swagger.json", version);
            //        //使用自定义的页面
            //        options.IndexStream = () => Assembly.GetExecutingAssembly().GetManifestResourceStream("XinLife.Common.swagger_index.html");
            //        options.RoutePrefix = "doc";
            //    });
            //});

            app.UseKnife4UI(options =>
            {
                new string[] { "XinLife" }.ToList().ForEach(version =>
                {
                    options.SwaggerEndpoint($"../swagger/{version}/swagger.json", version);
                    options.RoutePrefix = "doc";
                });
            });
        }
    }
    public class SwaggerAuthMiddleware
    {
        private readonly RequestDelegate next;

        public SwaggerAuthMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.Value.ToLower().Contains("doc/index.html"))
            {
                string key = Appsettings.app("AppSetting", "SwaggerKey"); /*SecurityUtils.GenerateAesKey();*/

                StringValues ticket;
                // 判断ticket是否正确
                if (context.Request.Query.TryGetValue("ticket", out ticket)) 
                {
                    try
                    {
                        string msg = SecurityUtils.AesDecrypt(Uri.UnescapeDataString(ticket), key);
                        JObject jobject = msg.ToJObject();
                        //判断时长
                        if (DateTimeOffset.FromFileTime(jobject.Value<long>("Expiration")).DateTime >= DateTime.Now)
                        {
                            await next.Invoke(context);
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        //解密失败
                    }
                }
                // 无权限，跳转swagger登录页
                RedirectSwaggerLogin(context);
            }
            else
            {
                await next.Invoke(context);
            }
        }
        public void RedirectSwaggerLogin(HttpContext context)
        {
            var returnUrl = context.Request.GetDisplayUrl(); //获取当前url地址 
            Uri uri = new Uri(returnUrl);
            context.Response.Redirect("../swg-login.html?returnUrl=" + uri.LocalPath);
        }
    }
}
